package com.cvtt.core;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;

public abstract class CoreEventHandler {

	private static final String LOG_TAG = "CoreEventHandler";

	protected Handler handler = new Handler();
	protected HandlerThread handlerThread;
	protected boolean bExit;

	protected CoreEventHandler() {
		handlerThread = new HandlerThread(this.getClass().getSimpleName());
		final String className = this.getClass().getSimpleName();
		handlerThread.start();
		handler = new Handler(handlerThread.getLooper()) {
			@Override
			public void handleMessage(Message msg) {
				try {
					handleCoreEvent(msg.what, msg.obj);
				}
				catch (Exception e) {
					Log.e(e.getMessage(), className + " handler msg.what : " + msg.what + " ====" + e.toString());
				}
			}
		};
	}

	public void onExit() {
		if (handlerThread != null)
			handlerThread.quit();
	}

	public boolean isExited() {
		return bExit;
	}

	public void postCoreEvent(int event, Object data) {
		//ULogger.d(LOG_TAG, "postCoreEvent:" + event);
		if (handler != null) {
			//ULogger.d(LOG_TAG, "handler.sendMessage:" + event);
			handler.sendMessage(handler.obtainMessage(event, data));
		}
	}

	public void postCoreEvent(int event, Object data, boolean reset) {
		if (handler != null) {
			if (reset)
				handler.removeMessages(event);
			handler.sendMessage(handler.obtainMessage(event, data));
		}
	}

	public void postCoreEvent(final int event, final Object data, long delayMillis) {
		//ULogger.d(LOG_TAG, "postCoreEvent:" + event);
		if (handler != null) {
			//ULogger.d(LOG_TAG, "handler.sendMessage:" + event);
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					handler.sendMessage(handler.obtainMessage(event, data));
				}
			}, delayMillis);
		}
	}

	public boolean postSyncCoreEvent(int event, Object data) {
		return true;
	}

	public abstract void handleCoreEvent(int event, Object data);
}
